<?php
declare (strict_types=1);

namespace app\common\service;

use app\common\exception\NotFoundException;
use app\common\helper\util\Tool;
use think\annotation\Inject;

/**
 * Class Attach
 *
 * @package app\common\service
 */
class Attach
{
    /**
     * @Inject()
     *
     * @var \app\common\logic\Attach
     */
    protected $attachLogic;

    /**
     * 查看资源
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/3/30
     *
     * @param string $filecode
     * @throws \Exception
     */
    public function view(string $filecode)
    {
        $id = Tool::decodeId($filecode);
        if (!$id) {
            throw new NotFoundException('资源不存在或已被删除');
        }
        // 获取文件的信息
        $attach  = $this->attachLogic->getAttachById($id);
        $fileurl = $attach->getAttr('redirect_url');
        if ($fileurl) {
            $playUrl = '';
            if (is_array($fileurl)) {
                foreach ($fileurl as $url) {
                    if ($url['definition'] == 'OD') {
                        $playUrl = $url['play_url'];
                        break;
                    }
                }

                if (!$playUrl) {
                    $playUrl = $fileurl[0]['play_url'];
                }
            } else {
                $playUrl = $fileurl;
            }
            // 跳转到对应资源
            header("location:" . $playUrl);
            exit;
        }

        throw new NotFoundException('资源不存在或已被删除');
    }

    /**
     * 获取附件预览显示播放的地址
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/6/3
     *
     * @param int $attachId
     * @throws \Exception
     */
    public function getViewUrl(int $attachId)
    {
        $url = $this->attachLogic->getAttachViewUrl($attachId);

        return BaseService::parseToData(['url' => $url], 1, '获取成功');
    }

    public function getFileUrl(int $attachId): string
    {
        $data = $this->attachLogic->findOrEmpty($attachId);

        return $data ? $data->fileurl : '';
    }
}